package com.c.ctgproject.ui.doorkeeper.car

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.provider.MediaStore
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import com.c.ctgproject.R
import com.c.ctgproject.adapter.doorkeeper.DoorkeeperCarListAdapter
import com.c.ctgproject.base.BaseMvpActivity
import com.c.ctgproject.entity.ListCarWaitingEntrance
import com.c.ctgproject.utils.*
import com.c.ctgproject.wiget.dialog.DoorkeeperDialog
import kotlinx.android.synthetic.main.activity_doorkeeper_acticity.*
import java.io.File
import java.io.IOException


/**
 *作者:LiBW
 *创建日期: 2020/8/15
 *描述: 门卫Activity 待入场车辆
 */
class CarWaitActivity : BaseMvpActivity<CarWaitPresenter>(), CarWaitContract.View, DoorkeeperDialog.DoorkeeperDialogCallback {
    private val cameraCode = 1
    private val takePhoto = 3
    private val photoName = "output_image.jpg"
    private var imageUri: Uri? = null
    private var carId = ""
    private var dialog: DoorkeeperDialog? = null

    //默认展示第一页
    private var page = 1

    //默认每页展示条数
    private var size = 10

    //待入场车辆列表信息
    private val mList: ArrayList<ListCarWaitingEntrance.DataBean.ListBean> = ArrayList()

    //快速搜索下的列表
    private val searchList: ArrayList<ListCarWaitingEntrance.DataBean.ListBean> = ArrayList()

    //备份列表
    private val copyList: ArrayList<ListCarWaitingEntrance.DataBean.ListBean> = ArrayList()

    //待入场车辆列表适配器
    private val mAdapter: DoorkeeperCarListAdapter by lazy { DoorkeeperCarListAdapter(this, mList) }

    //用于保存拍照图片的uri
    private var outputImage: File? = null

    //搜索字段
    private var plateNum = ""


    override fun getLayout(): Int {
        return R.layout.activity_doorkeeper_acticity
    }

    override fun event() {
        //设置透明状态栏
        changeTransparentStatusBar()
        mPresenter = CarWaitPresenter()
        mPresenter?.mView = this
        mDoorkeeperRV.adapter = mAdapter
        mDoorkeeperRV.layoutManager = LinearLayoutManager(this)
        //获取待入场车辆列表
        mPresenter?.getCarsInfo(page, size, plateNum)
    }

    override fun click() {
        //搜索框清除按钮
        mCleanIV.setOnClickListener {
            mCarNumberET.text = setEditText("")
        }
        //搜索输入框监听
        mCarNumberET.handlerText { searchText ->
            MyLog.d("搜索内容$searchText")
            if (searchText.isEmpty()) {
                mList.clear()
                mList.addAll(copyList)
                mAdapter.notifyDataSetChanged()
                return@handlerText
            }
            //清除临时列表
            searchList.clear()
            //搜索数据列表如果搜索内容存在则加入到临时列表
            copyList.forEach {
                if (it.ownerPlate.handlerNull().contains(searchText)||it.realPlate.handlerNull().contains(searchText)) {
                    MyLog.d("找到车牌${it.ownerPlate}")
                    searchList.add(it)
                }
            }
            //清除当前列表并将临时列表内容放入数据列表
            mList.clear()
            mList.addAll(searchList)
            //通知列表刷新
            mAdapter.notifyDataSetChanged()
        }
        //搜索按钮
        mSearchTV.setOnClickListener {
            page = 1
            plateNum = mCarNumberET.text.toString()
            mList.clear()
            mPresenter?.getCarsInfo(page, size, plateNum)
        }

        //下拉刷新监听
        mRefresh.setOnRefreshListener {
            MyLog.d("进行下拉刷新")
            page = 1
            plateNum = ""
            mCarNumberET.text = setEditText("")
            mList.clear()
            mPresenter?.getCarsInfo(page, size, plateNum, false)
        }
        //上拉加载
        mRefresh.setOnLoadMoreListener {
            MyLog.d("进行上啦加载")
            page++
            mPresenter?.getCarsInfo(page, size, plateNum, false)
        }
    }

    //车辆列表信息
    override fun carsInfoResult(cars: ListCarWaitingEntrance) {
        mRefresh.finishRefresh()
        mRefresh.finishLoadMore()
        if (cars.status == 0) {
            mList.addAll(cars.data.list)
            copyList.clear()
            copyList.addAll(mList)
            mAdapter.notifyDataSetChanged()
        } else {
            CustomToast.showToast(this, cars.msg.handlerNull())
        }
    }

    fun takePhoto(id: String) {
        carId = id
        checkPermission()
    }

    //检查相机权限
    private fun checkPermission(): Boolean {
        //判断是否有相机的权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
            outputImage = File(externalCacheDir, photoName)
            try {
                if (outputImage!!.exists()) {
                    outputImage!!.delete()
                }
                outputImage!!.createNewFile()
            } catch (e: IOException) {
                e.printStackTrace()
            }
            imageUri = if (Build.VERSION.SDK_INT >= 24) {
                FileProvider.getUriForFile(this, "com.ctgoe.paoding.gq.fileProvider", outputImage!!)
            } else {
                Uri.fromFile(outputImage)
            }
            val intent = Intent("android.media.action.IMAGE_CAPTURE")
            intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri)
            startActivityForResult(intent, takePhoto)
            return true
        } else {
            //没有权限则申请
            ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.CAMERA), cameraCode)
        }
        return false
    }

    //拍照结果回调
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == takePhoto) {
                MyLog.d("照片出来了")
                dialog = DoorkeeperDialog(this, carId, imageUri!!, this)
                dialog?.show()
            }
        }
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        MyLog.d("requestCode:$requestCode permissions:$permissions grantResults:$grantResults")
        if (requestCode == cameraCode) {
            checkPermission()
        }
    }

    override fun confirm() {
        CustomToast.showToast(this, "车辆入场成功")
        //确认入场后重新获取待入场车辆列表
        page = 1
        mList.clear()
        mPresenter?.getCarsInfo(page, size, plateNum)
    }

    override fun error(e: String) {
        CustomToast.showToast(this, e)
    }


}